package cn.kgc.vue.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 课工场
 * @date 2024/9/21
 * @description  jwt 工具类   用于生成 解析  校验 token
 */
@Component
public class JWTUtil {

    @Value("${jwt.secret}")
    private  String  secret;
    @Value("${jwt.expire}")
    private Integer  expireData;
    private HashMap<String,Object> header;

    public JWTUtil(){
        this.header = new HashMap<>();
        header.put("alg","HS256");
        header.put("type","JWT");
    }

    //创建token
    public String  createToken(HashMap<String,Object> claims){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DAY_OF_MONTH,expireData);
        Date time = instance.getTime();

        return   JWT.create()
                .withHeader(header)
                .withExpiresAt(time)
                .withClaim("userInfo",claims)
                .sign(Algorithm.HMAC256(secret));

    }

    // 解析token
    public Map<String,Object>  getClaims(String token){

       return JWT.decode(token)
                .getClaim("userInfo")
                .asMap();
    }

    // 校验token的方法
    public  void  verifyToken(String token){

        JWT.require(Algorithm.HMAC256(secret))
                .build()
                .verify(token);
    }
}
